package com.software.loginregister.fragment;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import retrofit2.Call;

import retrofit2.Callback;
import retrofit2.Response;

import com.bumptech.glide.Glide;
import com.software.loginregister.LoginActivity;
import com.software.loginregister.activity.AboutUsActivity;
import com.software.loginregister.activity.HelpCenterActivity;
import com.software.loginregister.activity.EditProfileActivity;
import com.software.loginregister.activity.FollowersActivity;
import com.software.loginregister.activity.HealthActivity;
import com.software.loginregister.activity.HistoryActivity;

import com.software.loginregister.activity.SettingActivity;
import com.software.loginregister.activity.WorksActivity;
import com.software.loginregister.R;
import com.software.loginregister.api.UserApi;
import com.software.loginregister.api.UserRelationApi;
import com.software.loginregister.databasesHelper.AppDatabase;
import com.software.loginregister.databasesHelper.UserDao;
import com.software.loginregister.entity.Result;
import com.software.loginregister.entity.User;

import com.software.loginregister.entity.vo.MyWorkDetailVO;
import com.software.loginregister.entity.vo.UserBasicVO;
import com.software.loginregister.entity.vo.UserFollowDTO;
import com.software.loginregister.util.RetrofitClient;
import com.software.loginregister.util.SharedPreferencesUtil;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * 个人中心Fragment
 * <p>
 * 功能：
 * 1. 展示用户基本信息（头像、昵称、签名）
 * 2. 提供各种功能入口：
 * - 编辑资料
 * - 关注/粉丝列表
 * - 动态
 * - 收藏
 * - 点赞
 * - 浏览历史
 * - 健康数据
 * 3. 处理登录/未登录状态
 * 4. 自动刷新用户信息
 * <p>
 * 交互流程：
 * 1. 进入页面自动加载用户信息
 * 2. 未登录状态显示登录提示
 * 3. 点击功能入口跳转对应页面
 * 4. 编辑资料后自动刷新信息
 *
 * @author 赵鑫，韩旭
 * @version 1.0
 * @since 2024-11-13
 */
public class MineFragment extends Fragment {
    private static final String TAG = "MineFragment";
    private ImageView avatarView;
    private TextView usernameView;
    private TextView signatureView;
    private UserApi userApi;
    private TextView followersCountTextView;
    private TextView followingCountTextView;
    private Long userId;
    private UserRelationApi userRelationApi;
    private TextView statusCountTextView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private UserDao userDao;
    private final Executor executor = Executors.newSingleThreadExecutor();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        userApi = RetrofitClient.getInstance().create(UserApi.class);
        userRelationApi = RetrofitClient.getInstance().create(UserRelationApi.class);
        userDao = AppDatabase.getDatabase(requireContext()).userDao();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);

        // 初始化 SwipeRefreshLayout
        swipeRefreshLayout = view.findViewById(R.id.swipeRefresh);
        setupSwipeRefresh();

        // 初始化视图
        initViews(view);

        // 获取用户ID并加载数据
        userId = SharedPreferencesUtil.getUserId(requireContext());
        if (userId != null && userId != -1) {
            // 先尝试从本地加载数据
            loadUserFromLocal();
            // 然后再从网络更新
            loadData();
        } else {
            showUnLoginState();
        }

        setupClickListeners(view);
        // 绑定点击事件
        view.findViewById(R.id.editProfile).setOnClickListener(v ->
                startActivity(new Intent(getActivity(), EditProfileActivity.class)));

        view.findViewById(R.id.followers).setOnClickListener(v ->
                startActivity(new Intent(getActivity(), FollowersActivity.class)));

        view.findViewById(R.id.following).setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), FollowersActivity.class);
            intent.putExtra("openTab", 1); // 1代表关注tab
            startActivity(intent);
        });


        view.findViewById(R.id.status).setOnClickListener(v ->
                startActivity(new Intent(getActivity(), WorksActivity.class)));

        view.findViewById(R.id.health_status).setOnClickListener(v ->
                startActivity(new Intent(getActivity(), HealthActivity.class)));
        // 浏览历史
        view.findViewById(R.id.ll_recent_view).setOnClickListener(v ->
                startActivity(new Intent(getActivity(), HistoryActivity.class)));

        view.findViewById(R.id.customer_service).setOnClickListener(v ->
                startActivity(new Intent(getActivity(), HelpCenterActivity.class)));

        view.findViewById(R.id.about_us).setOnClickListener(v ->
                startActivity(new Intent(getActivity(), AboutUsActivity.class)));

        view.findViewById(R.id.settings).setOnClickListener(v ->
                startActivity(new Intent(getActivity(), SettingActivity.class)));

        return view;
    }

    // 设置下拉刷新
    private void setupSwipeRefresh() {
        swipeRefreshLayout.setColorSchemeResources(R.color.theme_color);
        swipeRefreshLayout.setOnRefreshListener(this::loadData);
    }

    // 整合所有数据加载
    private void loadData() {
        if (!isAdded() || userId == null || userId == -1) {
            swipeRefreshLayout.setRefreshing(false);
            showUnLoginState();
            return;
        }

        // 显示刷新动画
        swipeRefreshLayout.setRefreshing(true);

        // 加载所有数据
        loadUserInfo();
        loadFollowStats();
        loadWorksCount();
    }

    private void loadWorksCount() {
        if (!isAdded() || userId == null) {
            statusCountTextView.setText("0");
            return;
        }

        Log.d("MineFragmentDebug", "开始获取用户作品数，userId: " + userId);
        try {
            RetrofitClient.getInstance().getWorksApi()
                    .getUserWorks(userId.intValue())  // 使用 intValue() 替代 Math.toIntExact()
                    .enqueue(new Callback<Result<List<MyWorkDetailVO>>>() {
                        @Override
                        public void onResponse(Call<Result<List<MyWorkDetailVO>>> call, Response<Result<List<MyWorkDetailVO>>> response) {
                            if (!isAdded()) {
                                return;
                            }

                            try {
                                if (response.isSuccessful() && response.body() != null) {
                                    Result<List<MyWorkDetailVO>> result = response.body();
                                    Log.d("MineFragmentDebug", "作品数据获取成功");

                                    if (result.getCode() == 1 && result.getData() != null) {
                                        int worksCount = result.getData().size();
                                        Log.d("MineFragmentDebug", "作品数：" + worksCount);
                                        statusCountTextView.setText(String.valueOf(worksCount));
                                    } else {
                                        Log.e("MineFragmentDebug", "获取作品数据失败：" + result.getMsg());
                                        statusCountTextView.setText("0");
                                    }
                                } else {
                                    Log.e("MineFragmentDebug", "响应不成功");
                                    statusCountTextView.setText("0");
                                }
                            } catch (Exception e) {
                                Log.e("MineFragmentDebug", "处理作品数据失败", e);
                                statusCountTextView.setText("0");
                            }
                        }

                        @Override
                        public void onFailure(Call<Result<List<MyWorkDetailVO>>> call, Throwable t) {
                            if (!isAdded()) {
                                return;
                            }
                            Log.e("MineFragmentDebug", "获取作品数失败", t);
                            statusCountTextView.setText("0");
                        }
                    });
        } catch (Exception e) {
            Log.e("MineFragmentDebug", "调用作品API失败", e);
            statusCountTextView.setText("0");
        }
    }

    private void loadFollowStats() {
        if (!isAdded() || userId == null) {
            followersCountTextView.setText("0");
            followingCountTextView.setText("0");
            return;
        }

        // 加载粉丝数
        Log.d(TAG, "开始加载粉丝数据");
        userRelationApi.getFollowers(userId).enqueue(new Callback<Result<List<UserFollowDTO>>>() {
            @Override
            public void onResponse(Call<Result<List<UserFollowDTO>>> call, Response<Result<List<UserFollowDTO>>> response) {
                if (!isAdded()) return;

                try {
                    if (response.isSuccessful() && response.body() != null) {
                        Result<List<UserFollowDTO>> result = response.body();
                        if (result.getCode() == 1 && result.getData() != null) {
                            followersCountTextView.setText(String.valueOf(result.getData().size()));
                        } else {
                            followersCountTextView.setText("0");
                            Log.e(TAG, "加载粉丝列表失败：" + result.getMsg());
                        }
                    } else {
                        followersCountTextView.setText("0");
                        Log.e(TAG, "加载粉丝列表失败：响应不成功");
                    }
                } catch (Exception e) {
                    followersCountTextView.setText("0");
                    Log.e(TAG, "处理粉丝列表数据失败", e);
                }
            }

            @Override
            public void onFailure(Call<Result<List<UserFollowDTO>>> call, Throwable t) {
                if (!isAdded()) return;
                followersCountTextView.setText("0");
                Log.e(TAG, "加载粉丝列表失败", t);
            }
        });

        // 加载关注数
        Log.d(TAG, "开始加载关注数据");
        userRelationApi.getFollowing(userId).enqueue(new Callback<Result<List<UserFollowDTO>>>() {
            @Override
            public void onResponse(Call<Result<List<UserFollowDTO>>> call, Response<Result<List<UserFollowDTO>>> response) {
                if (!isAdded()) return;

                try {
                    if (response.isSuccessful() && response.body() != null) {
                        Result<List<UserFollowDTO>> result = response.body();
                        if (result.getCode() == 1 && result.getData() != null) {
                            followingCountTextView.setText(String.valueOf(result.getData().size()));
                        } else {
                            followingCountTextView.setText("0");
                            Log.e(TAG, "加载关注列表失败：" + result.getMsg());
                        }
                    } else {
                        followingCountTextView.setText("0");
                        Log.e(TAG, "加载关注列表失败：响应不成功");
                    }
                } catch (Exception e) {
                    followingCountTextView.setText("0");
                    Log.e(TAG, "处理关注列表数据失败", e);
                }
            }

            @Override
            public void onFailure(Call<Result<List<UserFollowDTO>>> call, Throwable t) {
                if (!isAdded()) return;
                followingCountTextView.setText("0");
                Log.e(TAG, "加载关注列表失败", t);
            }
        });
    }

    private void initViews(View view) {
        avatarView = view.findViewById(R.id.avatar);
        usernameView = view.findViewById(R.id.username);
        signatureView = view.findViewById(R.id.signature);
        followersCountTextView = view.findViewById(R.id.tv_mine_followers_count);
        followingCountTextView = view.findViewById(R.id.tv_mine_following_count);
        statusCountTextView = view.findViewById(R.id.tv_mine_status_count);
    }

    private void loadUserInfo() {
        if (!isAdded() || userId == null) {
            return;
        }

        Log.d(TAG, "开始加载用户信息");
        userApi.getBasicInfo(userId).enqueue(new Callback<Result<UserBasicVO>>() {
            @Override
            public void onResponse(Call<Result<UserBasicVO>> call, Response<Result<UserBasicVO>> response) {
                if (!isAdded()) return;

                if (response.isSuccessful() && response.body() != null) {
                    Result<UserBasicVO> result = response.body();
                    if (result.getCode() == 1 && result.getData() != null) {
                        UserBasicVO userInfo = result.getData();
                        updateUi(userInfo);

                        // 保存用户信息到本地
                        saveUserToLocal(userInfo);
                    } else {
                        // 如果网络请求失败，尝试从本地加载
                        loadUserFromLocal();
                    }
                } else {
                    // 网络请求失败，尝试从本地加载
                    loadUserFromLocal();
                }
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onFailure(Call<Result<UserBasicVO>> call, Throwable t) {
                if (!isAdded()) return;
                Log.e(TAG, "加载用户信息失败", t);
                // 网络请求失败，尝试从本地加载
                loadUserFromLocal();
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    private void saveUserToLocal(UserBasicVO userInfo) {
        if (userInfo == null) return;

        executor.execute(() -> {
            try {
                User user = new User();
                user.setUserId(Long.valueOf(userInfo.getUserId()));
                user.setUserName(userInfo.getNickname());
                user.setAvatar(userInfo.getAvatar());
                // ... 设置其他需要的字段

                userDao.insert(user);
                Log.d(TAG, "用户信息已保存到本地数据库: " + user.getUserName());
            } catch (Exception e) {
                Log.e(TAG, "保存用户信息到本地数据库失败", e);
            }
        });
    }

    private void loadUserFromLocal() {
        executor.execute(() -> {
            try {
                User user = userDao.getUserById(userId);
                if (user != null) {
                    // 在主线程更新UI
                    new Handler(Looper.getMainLooper()).post(() -> {
                        UserBasicVO userBasicVO = new UserBasicVO();
                        userBasicVO.setUserId(Math.toIntExact(user.getUserId()));
                        userBasicVO.setNickname(user.getUserName());
                        userBasicVO.setAvatar(user.getAvatar());
                        // ... 设置其他需要的字段
                        updateUi(userBasicVO);
                    });
                } else {
                    new Handler(Looper.getMainLooper()).post(this::showUnLoginState);
                }
            } catch (Exception e) {
                Log.e(TAG, "从本地数据库加载用户信息失败", e);
                new Handler(Looper.getMainLooper()).post(this::showUnLoginState);
            }
        });
    }

    private void updateUi(UserBasicVO user) {
        if (!isAdded()) {
            return;
        }

        usernameView.setText(user.getNickname());
        signatureView.setText(user.getSignature());

        if (!TextUtils.isEmpty(user.getAvatar())) {
            Glide.with(this)
                    .load(user.getAvatar())
                    .placeholder(R.drawable.ic_defalut_avater)
                    .error(R.drawable.ic_defalut_avater)
                    .circleCrop()
                    .into(avatarView);
        }
    }

    private void showUnLoginState() {
        if (!isAdded()) return;

        // 清除本地存储的用户信息
        executor.execute(() -> {
            try {
                userDao.deleteAll();
                Log.d(TAG, "已清除本地数据库中的用户信息");
            } catch (Exception e) {
                Log.e(TAG, "清除本地数据库用户信息失败", e);
            }
        });

        // 更新UI为未登录状态
        avatarView.setImageResource(R.drawable.default_image);
        followersCountTextView.setText("0");
        followingCountTextView.setText("0");
        statusCountTextView.setText("0");

        // 点击头像跳转到登录页面
        avatarView.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
        });
    }

    private void setupClickListeners(View view) {
        view.findViewById(R.id.editProfile).setOnClickListener(v -> {
            if (userId == -1) {
                startActivity(new Intent(requireContext(), LoginActivity.class));
            } else {
                startActivity(new Intent(requireContext(), EditProfileActivity.class));
            }
        });
    }
}
